package me.huha.service.api.impl;

import java.util.HashMap;
import java.util.Map;

import me.huha.entity.IpMessageEntity;
import me.huha.service.api.IpCityApiService;
import me.huha.util.HttpClientUtils;
import me.huha.util.IpUtils;
import me.huha.util.JsonUtils;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class WhoisIpCityImpl implements IpCityApiService {
    
	private static Logger logger = Logger.getLogger(WhoisIpCityImpl.class);
	/**
	 * 太平洋网络接口URL
	 */
	private final static String TAOBAO_URL = "http://whois.pconline.com.cn/ipJson.jsp?json=true";

	/**
	 * 根据IP和类型查找地区信息
	 * 
	 * @param ip
	 * @param apiType
	 * @return
	 */
	public IpMessageEntity getAddresses(String ip) {
		IpMessageEntity ipMessage = new IpMessageEntity();
		Map<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("ip", ip);
		String retstring = HttpClientUtils.post(TAOBAO_URL, paramsMap);
		if (StringUtils.isEmpty(retstring) || "null".equals(retstring)) {
			return null;
		}
        try{
        	Map<String, Object> jsonMap = JsonUtils.parseJSON2Map(retstring);
    		if (jsonMap == null || jsonMap.isEmpty()) {
    			return null;
    		}
    		ipMessage.setRegion(jsonMap.get("pro").toString());
    		ipMessage.setCity(jsonMap.get("city").toString());
    		ipMessage.setCounty(jsonMap.get("region").toString());
    		ipMessage.setIsp(jsonMap.get("addr").toString());
    		ipMessage.setIpType(IpUtils.checkIpType(ip).getName());
    		ipMessage.setIp(ip);
    		ipMessage.setSource(WhoisIpCityImpl.class.getName());
        }catch(Exception e){
        	ipMessage = null;
        	logger.error(e);
        	logger.error("解析出错");
        }
		
		return ipMessage;
	}
}
